package com.edu.zhku.wms.controller;

import com.edu.zhku.wms.common.CommonResult;
import com.edu.zhku.wms.dto.LoginRequest;
import com.edu.zhku.wms.service.UserPrincipalService;
import com.edu.zhku.wms.vo.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Feng
 * @since 2021/10/26 17:02
 */

@Api(tags = "权限管理")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    UserPrincipalService userPrincipalService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public CommonResult login(@RequestBody @Validated LoginRequest loginRequest) {

        return CommonResult.success(userPrincipalService.login(loginRequest));
    }

    @ApiOperation("登出")
    @DeleteMapping("/logout")
    public CommonResult logout(HttpServletRequest request) {
        try {
            userPrincipalService.logout(request);
        } catch (Exception e) {
            return CommonResult.unauthorized();
        }
        return CommonResult.success();
    }

    @ApiOperation("获取已登录的用户的信息")
    @GetMapping("/info")
    public CommonResult info(HttpServletRequest request) {
        UserInfo info = userPrincipalService.getLoggedInfo(request);
        if (info == null) {
            return CommonResult.unauthorized();
        }
        return CommonResult.success(info);
    }
}
